package pers.ljf.escloud.service.modules.app.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import pers.ljf.escloud.common.req.EntSaveRequest;
import pers.ljf.escloud.common.utils.DateUtils;
import pers.ljf.escloud.dao.entity.app.*;
import pers.ljf.escloud.dao.entity.sys.SysUserEntity;
import pers.ljf.escloud.dao.mapper.app.EnterpriseMapper;
import pers.ljf.escloud.service.dto.Query;
import pers.ljf.escloud.service.modules.app.*;
import pers.ljf.escloud.service.modules.sys.SysUserRoleService;
import pers.ljf.escloud.service.modules.sys.SysUserService;
import pers.ljf.escloud.service.util.PageUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laijinfan1
 * @since 2022-02-14
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {

    @Resource
    private UserService userService;

    @Override
    public void save(EntSaveRequest form) {
        Enterprise enterprise = new Enterprise();
        BeanUtils.copyProperties(form,enterprise);
        save(enterprise);
    }

    @Override
    public void updateSpace(Long userId, long sizeMB) {
        User user = userService.getById(userId);
        Long entId = user.getEntId();
        Enterprise enterprise = getById(entId);
        long spaceNew = enterprise.getSpaceUsed() + sizeMB < 0 ? 0 : enterprise.getSpaceUsed() + sizeMB;
        Assert.isTrue((spaceNew) <= enterprise.getSpaceAmount(), "企业新已用空间超出限制");
        enterprise.setSpaceUsed(spaceNew);
        updateById(enterprise);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String entName = (String)params.get("entName");

        IPage<Enterprise> page = this.page(
                new Query<Enterprise>().getPage(params),
                new QueryWrapper<Enterprise>()
                        .like(StringUtils.isNotBlank(entName),"name", entName)
        );
        for (Enterprise enterprise : page.getRecords()) {
            User user = userService.getById(enterprise.getAdminId());
            enterprise.setAdminUsername(user.getUsername());
            enterprise.setEstablishDateOuter(DateUtils.format(enterprise.getEstablishDate(),DateUtils.DATE_PATTERN));
        }
        return new PageUtils(page);
    }

    @Resource
    private DepartmentService departmentService;
    @Resource
    private BucketService bucketService;
    @Resource
    private BucketDeptService bucketDeptService;

    @Resource
    private FileService fileService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserRoleService sysUserRoleService;

    @Override
    @Transactional
    public void deleteBatch(Long[] entIds) {
        for (Long entId : entIds) {
            Enterprise ent = getById(entId);
            //删用户
            List<SysUserEntity> sysUsers = sysUserService.list(new QueryWrapper<SysUserEntity>().eq("ent_id", ent.getId()));
            List<Long> sysUserIds = sysUsers.stream().map(SysUserEntity::getUserId).collect(Collectors.toList());
            sysUserRoleService.removeByIds(sysUserIds);
            sysUserService.removeByIds(sysUserIds);
            userService.remove(new QueryWrapper<User>().eq("ent_id",ent.getId()));
            //删bucket与bucket关联
            List<Bucket> bucks = bucketService.list(new QueryWrapper<Bucket>().eq("enterprise_id", ent.getId()));
            List<Long> bucketIds = bucks.stream().map(Bucket::getId).collect(Collectors.toList());
            //删文件
            for (Bucket buck : bucks) {
                String bucketName = buck.getBucketName();
                String keyPrefix = ent.getName();
                OSS ossClient = new OSSClientBuilder().build(buck.getEndpoint(), buck.getAccessKeyId(), buck.getAccessKeySecret());
                fileService.deleteByPrefix(null,bucketName,ent.getName(),ossClient,false);
            }
            bucketDeptService.remove(new QueryWrapper<BucketDept>().in("bucket_id",bucketIds));
            bucketService.removeByIds(bucketIds);
            //删部门
            departmentService.remove(new QueryWrapper<Department>().eq("enterprise_id",ent.getId()));
            //删企业
            removeById(entId);
        }
    }
}
